/*
 * @Author: wangzhichiao<https://github.com/wzc570738205>
 * @Date: 2020-11-15 21:38:29
 * @LastEditors: wangzhichiao<https://github.com/wzc570738205>
 * @LastEditTime: 2021-09-14 11:28:04
 */

let code =
  "[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“’。，、？-] ";
const keyM: string[] = [
  "联系电话", "电话", "联系人手机号码", "联系人", "手机号码", "手机号", "手机",
  "邮编", "姓名", "收货人", "收件人"
];
// 地址特殊处理
const keyA: string[] = [
  "收货地址", "收件地址", "退货地址", "所在地区", "所在地", "联系地址", "送货地址", "详细地址", "地区", "地址"
];
const keyC: string[] = ["省 ", "市 ", "区 ", "道 ", "县 ", "镇 ", "处 ", "栋 "];
const keyD: string[] = ["重庆 ", "上海 ", "北京 ", "天津 ", "市辖区", "86-", "(86)", "（", "）", "&middot;"];
let keyMs: string[] = [];
let keyAs: string[] = [];

keyM.forEach((e) => {
  for (let i = 0; i < code.length; i++) {
    keyMs.push(e + code[i]);
    keyMs.push(e + code[i] + code[i]);
  }
  keyMs.push(e);
});

keyA.forEach((e) => {
  for (let i = 0; i < code.length; i++) {
    keyAs.push(e + code[i] + " ");
    keyAs.push(e + code[i] + "  ");
    keyAs.push(e + code[i] + "   ");
    keyAs.push(e + code[i]);
    keyAs.push(e + code[i] + code[i]);
  }
  keyAs.push(e);
});

function formatByKey(s: string): string {
  s = s.replace(/[\r\n\t]/g, "");

  for (const key of keyMs) {
    s = s.replace(key, " ");
  }

  let number = 0;
  for (const key of keyAs) {
    if (s.includes(key)) {
      number++;
      if (number > 1) {
        s = s.replace(key, "");
      } else {
        s = s.replace(key, " ");
      }
    }
  }

  // 过滤掉直辖市
  for (const d of keyD) {
    s = s.replace(d, "");
  }

  // 过滤掉市区县后面空格
  let indexCount = 0;
  for (let index = 0; index < 3; index++) {
    for (const c of keyC) {
      if (s.includes(c)) {
        indexCount++;
      }
      const str = c.trim();
      s = s.replace(c, str);
    }
  }

  if (indexCount > 3) {
    s = s.replace(/\s+/g, "");
  }

  return s;
}

export default formatByKey;